<?php
/***************************************************************************
 * @Description:
 * 
 * @FileName:         ValidateController.php
 * @Author :          liyong5@staff.sina.com.cn
 * @CreatedTime:      2018年08月09日 星期四 18时22分31秒
 ************************************************************************/

namespace app\modules\core\controllers;

use Yii;
use app\modules\core\models\Validator;

class ValidatorController extends DefaultController
{
    public function actionList() {
        $validators = Validator::find()
            ->where([])
            ->all();

        return $this->render('list', ['validators' => $validators]);
    }

    public function actionInfo() {
        $request = Yii::$app->request;

        $validator = Validator::find()
            ->where(['id' => $request->get('id')])
            ->one();
        if (! $validator) {
            return $this->redirect(['core/validator/list']);
        }

        return $this->render('content', ['validator' => $validator]);
    }

    // 安装一个验证器
    public function actionInstall() {
        $request = Yii::$app->request;

        $validator = new Validator();
        if (null === $request->post('ns')) {
            return $this->render('install', ['validator' => $validator]);
        }

        if (! $validator->load($request->post())) {
            return $this->render('install', ['validator' => $validator]);
        }

        // params
        $validate['params'] = json_decode($request->post('params'));
        $validate['enable'] = '1';

        if ($validator->validate() && $validator->save()) {
            return $this->redirect(['/core/validator/list']);
        }
        return $this->render('install', ['validator' => $validator]);
    }

    public function actionEnable() {
        $request = Yii::$app->request;

        $validator = Validator::find()
            ->where(['id' => $request->post('id')])
            ->one();
        if (! $validator) {
            return $this->redirect(['/core/validator/list']);
        }


        $validator['enable'] = '1';
        $res = $validator->save();
        return $this->redirect(['/core/validator/info', 'id' => $request->post('id')]);
    }

    public function actionDisable() {
        $request = Yii::$app->request;

        $validator = Validator::find()
            ->where(['id' => $request->post('id')])
            ->one();
        if (! $validator) {
            return $this->redirect(['/core/validator/list']);
        }

        $validator['enable'] = '0';
        $validator->save();
        return $this->redirect(['/core/validator/info', 'id' => $request->post('id')]);
    }
}
